<template>
  <view class="reader-container">
    <!-- 阅读内容 -->
    <view class="reading-content" @click="toggleSettings">
      <view class="content-wrapper">
        <text class="book-title">{{ bookInfo.title }}</text>
        <text class="chapter-title">{{ currentChapter }}</text>
        <view class="text-content">
          <text 
            v-for="(paragraph, index) in currentContent" 
            :key="index"
            class="paragraph"
          >
            {{ paragraph }}
          </text>
        </view>
      </view>
    </view>

    <!-- 阅读进度条 -->
    <view class="progress-bar">
      <u-slider
        v-model="readingProgress"
        :min="0"
        :max="100"
        :step="1"
        @change="onProgressChange"
        activeColor="#007aff"
        inactiveColor="#e0e0e0"
      ></u-slider>
      <view class="progress-text">
        <text>{{ Math.round(readingProgress) }}%</text>
        <text>{{ currentPage }}/{{ totalPages }}</text>
      </view>
    </view>

    <!-- 阅读设置面板 -->
    <u-popup v-model="showSettings" mode="bottom" height="60%">
      <view class="settings-panel">
        <view class="panel-header">
          <text class="panel-title">阅读设置</text>
          <u-icon name="close" size="24" @click="showSettings = false"></u-icon>
        </view>
        
        <!-- 字体大小设置 -->
        <view class="setting-item">
          <text class="setting-label">字体大小</text>
          <view class="font-size-controls">
            <u-button 
              size="mini" 
              @click="decreaseFontSize"
              :disabled="fontSize <= 14"
            >
              A-
            </u-button>
            <text class="font-size-display">{{ fontSize }}px</text>
            <u-button 
              size="mini" 
              @click="increaseFontSize"
              :disabled="fontSize >= 24"
            >
              A+
            </u-button>
          </view>
        </view>
        
        <!-- 行间距设置 -->
        <view class="setting-item">
          <text class="setting-label">行间距</text>
          <u-slider
            v-model="lineHeight"
            :min="1.2"
            :max="2.5"
            :step="0.1"
            @change="onLineHeightChange"
            activeColor="#007aff"
            inactiveColor="#e0e0e0"
          ></u-slider>
          <text class="setting-value">{{ lineHeight.toFixed(1) }}</text>
        </view>
        
        <!-- 背景颜色选择 -->
        <view class="setting-item">
          <text class="setting-label">背景颜色</text>
          <view class="color-options">
            <view 
              v-for="(color, index) in backgroundColors" 
              :key="index"
              class="color-option"
              :class="{ active: currentBackground === color.name }"
              :style="{ backgroundColor: color.value }"
              @click="selectBackground(color.name)"
            ></view>
          </view>
        </view>
        
        <!-- 字体颜色选择 -->
        <view class="setting-item">
          <text class="setting-label">字体颜色</text>
          <view class="color-options">
            <view 
              v-for="(color, index) in textColors" 
              :key="index"
              class="color-option"
              :class="{ active: currentTextColor === color.name }"
              :style="{ backgroundColor: color.value }"
              @click="selectTextColor(color.name)"
            ></view>
          </view>
        </view>
        
        <!-- 翻页方式 -->
        <view class="setting-item">
          <text class="setting-label">翻页方式</text>
          <u-radio-group v-model="pageTurnMode">
            <u-radio 
              v-for="(mode, index) in pageTurnModes" 
              :key="index"
              :name="mode.value"
              :label="mode.label"
            ></u-radio>
          </u-radio-group>
        </view>
      </view>
    </u-popup>

    <!-- 章节选择弹窗 -->
    <u-popup v-model="showChapterList" mode="bottom" height="70%">
      <view class="chapter-panel">
        <view class="panel-header">
          <text class="panel-title">章节列表</text>
          <u-icon name="close" size="24" @click="showChapterList = false"></u-icon>
        </view>
        
        <scroll-view class="chapter-list" scroll-y>
          <view 
            v-for="(chapter, index) in chapters" 
            :key="index"
            class="chapter-item"
            :class="{ active: currentChapterIndex === index }"
            @click="selectChapter(index)"
          >
            <text class="chapter-name">{{ chapter.title }}</text>
            <text class="chapter-progress">{{ chapter.progress }}%</text>
          </view>
        </scroll-view>
      </view>
    </u-popup>

    <!-- 顶部工具栏 -->
    <view class="top-toolbar" v-show="showTopBar">
      <view class="toolbar-left">
        <u-icon name="arrow-left" size="24" @click="goBack"></u-icon>
      </view>
      <view class="toolbar-center">
        <text class="book-title-text">{{ bookInfo.title }}</text>
      </view>
      <view class="toolbar-right">
        <u-icon name="list" size="24" @click="showChapterList = true"></u-icon>
        <u-icon name="setting" size="24" @click="showSettings = true"></u-icon>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue';

// 页面参数
const bookId = ref('');
const bookTitle = ref('');

// 书籍信息
const bookInfo = ref({
  title: '',
  content: '',
  chapters: []
});

// 阅读状态
const currentChapterIndex = ref(0);
const currentPage = ref(1);
const totalPages = ref(1);
const readingProgress = ref(0);
const showSettings = ref(false);
const showChapterList = ref(false);
const showTopBar = ref(false);

// 阅读设置
const fontSize = ref(18);
const lineHeight = ref(1.6);
const currentBackground = ref('white');
const currentTextColor = ref('black');
const pageTurnMode = ref('scroll');

// 背景颜色选项
const backgroundColors = ref([
  { name: 'white', value: '#ffffff' },
  { name: 'sepia', value: '#f4ecd8' },
  { name: 'night', value: '#1a1a1a' },
  { name: 'green', value: '#e8f5e8' }
]);

// 字体颜色选项
const textColors = ref([
  { name: 'black', value: '#333333' },
  { name: 'brown', value: '#5d4037' },
  { name: 'white', value: '#ffffff' },
  { name: 'gray', value: '#666666' }
]);

// 翻页方式
const pageTurnModes = ref([
  { label: '滚动翻页', value: 'scroll' },
  { label: '点击翻页', value: 'click' }
]);

// 计算属性
const currentChapter = computed(() => {
  if (bookInfo.value.chapters && bookInfo.value.chapters[currentChapterIndex.value]) {
    return bookInfo.value.chapters[currentChapterIndex.value].title;
  }
  return '第一章';
});

const currentContent = computed(() => {
  if (bookInfo.value.chapters && bookInfo.value.chapters[currentChapterIndex.value]) {
    const content = bookInfo.value.chapters[currentChapterIndex.value].content;
    return content.split('\n').filter(p => p.trim());
  }
  return bookInfo.value.content ? bookInfo.value.content.split('\n').filter(p => p.trim()) : [];
});

const chapters = computed(() => {
  return bookInfo.value.chapters || [];
});

// 页面加载时初始化
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  bookId.value = options.id;
  bookTitle.value = decodeURIComponent(options.title || '');
  
  loadBook();
  loadReadingProgress();
  loadReadingSettings();
});

// 加载书籍内容
const loadBook = () => {
  try {
    const books = uni.getStorageSync('books') || [];
    const book = books.find(b => b.id === bookId.value);
    
    if (book) {
      bookInfo.value = book;
      
      // 如果没有章节，创建默认章节
      if (!book.chapters || book.chapters.length === 0) {
        createDefaultChapters(book.content);
      }
      
      calculateTotalPages();
    } else {
      uni.showToast({
        title: '书籍不存在',
        icon: 'none'
      });
      setTimeout(() => {
        goBack();
      }, 1500);
    }
  } catch (e) {
    console.error('加载书籍失败:', e);
  }
};

// 创建默认章节
const createDefaultChapters = (content) => {
  const paragraphs = content.split('\n').filter(p => p.trim());
  const chapterSize = 50; // 每章50段
  const chapters = [];
  
  for (let i = 0; i < paragraphs.length; i += chapterSize) {
    const chapterParagraphs = paragraphs.slice(i, i + chapterSize);
    chapters.push({
      title: `第${Math.floor(i / chapterSize) + 1}章`,
      content: chapterParagraphs.join('\n'),
      progress: 0
    });
  }
  
  bookInfo.value.chapters = chapters;
};

// 计算总页数
const calculateTotalPages = () => {
  // 这里可以根据实际内容长度和页面大小来计算
  // 简化处理，假设每章10页
  totalPages.value = chapters.value.length * 10;
};

// 加载阅读进度
const loadReadingProgress = () => {
  try {
    const progress = uni.getStorageSync('readingProgress') || {};
    if (progress[bookId.value]) {
      readingProgress.value = progress[bookId.value].progress || 0;
      currentChapterIndex.value = progress[bookId.value].chapter || 0;
      currentPage.value = progress[bookId.value].page || 1;
    }
  } catch (e) {
    console.error('加载阅读进度失败:', e);
  }
};

// 保存阅读进度
const saveReadingProgress = () => {
  try {
    const progress = uni.getStorageSync('readingProgress') || {};
    progress[bookId.value] = {
      progress: readingProgress.value,
      chapter: currentChapterIndex.value,
      page: currentPage.value,
      timestamp: Date.now()
    };
    uni.setStorageSync('readingProgress', progress);
  } catch (e) {
    console.error('保存阅读进度失败:', e);
  }
};

// 加载阅读设置
const loadReadingSettings = () => {
  try {
    const settings = uni.getStorageSync('readingSettings') || {};
    fontSize.value = settings.fontSize || 18;
    lineHeight.value = settings.lineHeight || 1.6;
    currentBackground.value = settings.background || 'white';
    currentTextColor.value = settings.textColor || 'black';
    pageTurnMode.value = settings.pageTurnMode || 'scroll';
  } catch (e) {
    console.error('加载阅读设置失败:', e);
  }
};

// 保存阅读设置
const saveReadingSettings = () => {
  try {
    const settings = {
      fontSize: fontSize.value,
      lineHeight: lineHeight.value,
      background: currentBackground.value,
      textColor: currentTextColor.value,
      pageTurnMode: pageTurnMode.value
    };
    uni.setStorageSync('readingSettings', settings);
  } catch (e) {
    console.error('保存阅读设置失败:', e);
  }
};

// 进度变化处理
const onProgressChange = (value) => {
  readingProgress.value = value;
  // 根据进度计算当前章节和页面
  const chapterIndex = Math.floor((value / 100) * chapters.value.length);
  currentChapterIndex.value = Math.max(0, Math.min(chapterIndex, chapters.value.length - 1));
  currentPage.value = Math.floor((value / 100) * totalPages.value);
  
  saveReadingProgress();
};

// 字体大小调整
const increaseFontSize = () => {
  if (fontSize.value < 24) {
    fontSize.value += 2;
    saveReadingSettings();
  }
};

const decreaseFontSize = () => {
  if (fontSize.value > 14) {
    fontSize.value -= 2;
    saveReadingSettings();
  }
};

// 行间距调整
const onLineHeightChange = (value) => {
  lineHeight.value = value;
  saveReadingSettings();
};

// 背景颜色选择
const selectBackground = (colorName) => {
  currentBackground.value = colorName;
  saveReadingSettings();
};

// 字体颜色选择
const selectTextColor = (colorName) => {
  currentTextColor.value = colorName;
  saveReadingSettings();
};

// 选择章节
const selectChapter = (index) => {
  currentChapterIndex.value = index;
  const progress = (index / chapters.value.length) * 100;
  readingProgress.value = progress;
  currentPage.value = Math.floor((progress / 100) * totalPages.value);
  
  saveReadingProgress();
  showChapterList.value = false;
};

// 切换设置面板
const toggleSettings = () => {
  showSettings.value = !showSettings.value;
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 监听设置变化
watch([fontSize, lineHeight, currentBackground, currentTextColor, pageTurnMode], () => {
  saveReadingSettings();
});

// 页面卸载时保存进度
onUnmounted(() => {
  saveReadingProgress();
});

// 定时保存进度
setInterval(() => {
  saveReadingProgress();
}, 30000); // 每30秒保存一次
</script>

<style lang="scss" scoped>
.reader-container {
  height: 100vh;
  background-color: v-bind('backgroundColors.find(c => c.name === currentBackground)?.value || "#ffffff"');
  color: v-bind('textColors.find(c => c.name === currentTextColor)?.value || "#333333"');
  position: relative;
}

.reading-content {
  height: calc(100vh - 120rpx);
  padding: 40rpx;
  overflow-y: auto;
  
  .content-wrapper {
    .book-title {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 20rpx;
      color: v-bind('textColors.find(c => c.name === currentTextColor)?.value || "#333333"');
    }
    
    .chapter-title {
      display: block;
      font-size: 28rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 40rpx;
      color: v-bind('textColors.find(c => c.name === currentTextColor)?.value || "#333333"');
    }
    
    .text-content {
      .paragraph {
        display: block;
        font-size: v-bind('fontSize + "px"');
        line-height: v-bind('lineHeight');
        margin-bottom: 20rpx;
        text-align: justify;
        color: v-bind('textColors.find(c => c.name === currentTextColor)?.value || "#333333"');
      }
    }
  }
}

.progress-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx;
  border-top: 1rpx solid #e0e0e0;
  
  .progress-text {
    display: flex;
    justify-content: space-between;
    margin-top: 10rpx;
    font-size: 24rpx;
    color: #666;
  }
}

.top-toolbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 20rpx 40rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 100;
  
  .toolbar-center {
    .book-title-text {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .toolbar-left,
  .toolbar-right {
    display: flex;
    gap: 20rpx;
  }
}

.settings-panel,
.chapter-panel {
  background: white;
  border-radius: 16rpx 16rpx 0 0;
  padding: 30rpx;
  
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .panel-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
}

.setting-item {
  margin-bottom: 30rpx;
  
  .setting-label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .setting-value {
    display: block;
    text-align: center;
    font-size: 24rpx;
    color: #666;
    margin-top: 10rpx;
  }
}

.font-size-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
  
  .font-size-display {
    font-size: 28rpx;
    color: #333;
    min-width: 80rpx;
    text-align: center;
  }
}

.color-options {
  display: flex;
  gap: 20rpx;
  
  .color-option {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    border: 3rpx solid transparent;
    cursor: pointer;
    
    &.active {
      border-color: #007aff;
    }
  }
}

.chapter-list {
  max-height: 500rpx;
  
  .chapter-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.active {
      background-color: #f0f8ff;
    }
    
    .chapter-name {
      font-size: 28rpx;
      color: #333;
    }
    
    .chapter-progress {
      font-size: 24rpx;
      color: #666;
    }
  }
}
</style>
